package helper

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/thedevsaddam/gojsonq"
)

// @Title       esUserGroup
// @author      liqi 2018/12/18 13:45
// @Description es原生查询语句groupBy
// @Param	userType 数据类型 1：十音 2：cps
// @Param	Sex 性别 1：男 2：女
// @Param	Start End 查询开始结束时间

func EsUserGroup(userType int, Sex int, Start string, End string, url string) int {
	sendJson := make(map[string]interface{})
	sendJson["query"] = map[string]interface{}{
		"bool": map[string]interface{}{
			"must": []interface{}{
				map[string]interface{}{
					"term": map[string]interface{}{"type": userType},
				},
				map[string]interface{}{
					"term": map[string]interface{}{"sex": Sex},
				},
			},
			"filter": map[string]interface{}{
				"range": map[string]interface{}{
					"created_at": map[string]interface{}{
						"from": Start,
						"to":   End,
					},
				},
			},
		},
	}
	sendJson["size"] = 0
	sendJson["aggs"] = map[string]interface{}{
		"data_group": map[string]interface{}{
			"terms": map[string]interface{}{
				"field": "user_id",
			},
		},
	}
	//fmt.Println("sendJson：", sendJson)
	requestData, _ := json.Marshal(sendJson)
	reader := bytes.NewReader(requestData)
	head := make(map[string]string)
	head["Content-Type"] = "application/json; charset=utf-8"
	result, status := httpSend(url, reader, head)
	//fmt.Println("result：", string(result))
	if status == 200 {
		jq := gojsonq.New().JSONString(result).From("aggregations.data_group.buckets")
		jqcount := jq.Count()
		fmt.Println("bucketsCount：", jqcount)
		return jqcount
	}
	return 0

}
